const _ = require('lodash');


module.exports = app => {
    const {router, middleware} = app;
    const prefix = '/api/report-comment/:report_id';

    const checkReportExits = async (ctx, next) => {
        const {report_id} = ctx.params;
        const report = await ctx.app.model.Report.findByPk(report_id);
        if (!report)
            return ctx.helper.error('不存在的日志');
        ctx.report = report;
        await next();
    };

    //查看评论
    router.get(prefix + '/:timestamp', checkReportExits, middleware.api(), async ctx => {
        const {timestamp} = ctx.params;
        const {User} = ctx.app.model;
        ctx.body = await ctx.report.getComment({
            order: [['created_at', 'asc']],
            where: {created_at: {[ctx.app.Sequelize.Op.lt]: new Date(timestamp)}},
            include: [{model: User, attributes: ['id', 'username']}],
        });
    });

    //发表评论
    router.post(prefix, middleware.api(), checkReportExits, async ctx => {
        const data = ctx.request.body;
        if (_.isEmpty(data.content))
            return ctx.helper.error('评论内容不能为空');
        const {ReportComment} = ctx.app.model;
        await ReportComment.create({
            content: data.content,
            user_id: ctx.user.id,
            report_id: ctx.report.id
        });
        ctx.body = 'ok';
    });
};